import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common'
import e, { Response, Request } from 'express'
import { LoggerService } from 'src/common/modules/logger/logger.service';
import { IHttpLog } from 'src/common/modules/logger/logger.types';
import config from 'src/config';
import { randomString } from 'src/utils';
import log from 'src/utils/log';
@Catch()
export class AllExceptionFilter implements ExceptionFilter {
	constructor(
		private readonly loggerService: LoggerService,
	){}
	catch(exception: any, host: ArgumentsHost) {
		// console.log("exception",exception)
		const context = host.switchToHttp()
		const response = context.getResponse<Response>()
		const req = context.getRequest<Request>()
		const isHttpError=exception instanceof HttpException
		const status =isHttpError? exception.getStatus()
				: HttpStatus.INTERNAL_SERVER_ERROR;
		const message = isHttpError?exception.getResponse():exception.message
		let errorData = isHttpError?JSON.parse(JSON.stringify(exception,null,2)):exception.stack.toString()
		// //@ts-ignore
		let logParams:IHttpLog={
			//@ts-ignore
			trackId:req.trackId,
			//@ts-ignore
			ip:req.headers["x-real-ip"]||req.headers["x-forwarded-for"]||"",
			//@ts-ignore
			user: req.user?._id||"",
			url: req.url,
			method: req.method,
			//@ts-ignore
			timeMs: Date.now()-req.requestTime,
			headers: req.headers,
			params: req.params,
			body: req.body,
			responseFrom:"db",
			responseCode:status,
			error:errorData
		}
		this.loggerService.writeHttpLog(logParams)
		if(!isHttpError){
			if(!config.isServer){
				console.error(errorData)
			}
			response.status(500).json({
				statusCode:500,
				message:'服务器内部错误'
			})
		}else{
			response.status(status).json(message)
		}
	}
}
